package cn.edu.ptu.jobfairs.web;

import cn.edu.ptu.jobfairs.basic.common.Errors;
import cn.edu.ptu.jobfairs.basic.common.Result;
import cn.edu.ptu.jobfairs.basic.common.VisibleException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.ServletException;
import java.util.UUID;

import static cn.edu.ptu.jobfairs.basic.common.Errors.*;


/**
 * Created by Lin Chenxiao on 2020-05-27
 **/
@Slf4j
@RestControllerAdvice
public class ExceptionController {
    @ExceptionHandler(value = Exception.class)
    public Result handle(Exception e) {
        if (e instanceof AccessDeniedException) return Result.fail(UNAUTHORIZED);
        else if (e instanceof BeansException) return Result.fail(CLIENT_ERROR, "请求路径或参数错误");
        else if (e instanceof ServletException) return Result.fail(CLIENT_ERROR, "请求路径或方法错误");
        //else if (e instanceof MethodArgumentNotValidException) return BasicResult.fail(CLIENT_ERROR, e.getMessage());
        else if (e instanceof HttpMessageNotReadableException)
            return Result.fail(CLIENT_ERROR, "请求参数结构错误");
        else if (e instanceof VisibleException) {
            Errors errors = ((VisibleException)e).getError();
            Result result = Result.fail(errors);
            if (errors == DATABASE_ERROR) packTraceId(result, e);
            return result;
        }
        else {
            Result result = Result.fail(SERVER_ERROR, "服务器发生错误");
            packTraceId(result, e);
            return result;
        }
    }

    private void packTraceId(Result result, Exception e) {
        String uuid = UUID.randomUUID().toString().replace("-", "");
        result.setTraceId(uuid);
        log.error(uuid, e);
    }
}
